const express = require('express');
const router = express.Router();
const utils = require('../../utils');

const filters = [
    {
        Name: '名称',
        Type: 'String',
    },
    {
        Name: '详情',
        Type: 'String',
    },
];

// online training
router.get('/',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'oltraining'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } }
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '时间',
            '名称',
            '类型',
            '详情',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('oltraining', false, (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.日期 = doc.时间 || doc.LastUpdateDate;
            doc.详情 = utils.repalceHtmlToText(doc.详情 || '');
            delete doc.LastUpdateDate;
            delete doc.时间;
        }
    })
);

// online training details
router.get('/:id',
    (req, res, next) => {
        res.locals.filter = { id: req.params.id, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } };
        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '推荐指数',
            '时间',
            
            '名称',
            '类型',
            '详情',
            '附件',
        ];
        res.locals.options = {
            lean: true
        };

        return next();
    },
    router.FindDocuments('oltraining', false, async (req, res) => {
        if(res.locals.data && res.locals.data.total) {
            res.locals.data = res.locals.data.docs[0];

            // application
            const application = req.user && await res.app.models.trainingapplication.findOne({
                培训: res.locals.data.名称,
                User: req.user.id,
            });

            if (application) {
                res.locals.data.applyStatus = application.Status;

                if (application.Status === '-1' || application.Status === '1') {
                    res.locals.data.comments = application.Steps && application.Steps[2] && application.Steps[2].Reason1 || '';
                }
            }
        } else {
            res.locals.data = {};
        }
    }),
);

// related
router.get('/related/:id',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'oltraining'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } },
            { id: {$ne: req.params.id }},
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '时间',
            '日期',
            '名称',
            '类型',
            '详情',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true,
        };

        return next();
    },
    router.FindDocuments('oltraining', false, async (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.详情 = utils.repalceHtmlToText(doc.详情 || '');
            doc.日期 = doc.时间 || doc.日期 || doc.LastUpdateDate;
            delete doc.LastUpdateDate;
            delete doc.时间;
        }

        await utils.getDictLabel(req, res, '类型', '在线培训类型');
    })
);

router.post('/apply/:id', 
    async (req, res, next) => {
        // 必须登录才能申请服务
        if (!req.user || !req.user.id) {
            res.makeError(401, '登录后方可申请。');
            return next('route');
        }

        const sid = req.params.id;
        if (!sid) {
            res.makeError(400, '请选择培训。');
            return next('route');
        }

        const theTraining = await res.app.models['oltraining'].findOne({ id: sid, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } });
        if (!theTraining) {
            res.makeError(403, '选择的培训不存在。');
            return next('route');
        }

        const appFlow = await res.app.models['flow'].findOne({ Code: 'trainingapplication' });
        if (!appFlow) {
            await res.makeError(404, '此功能尚未启用！');
            return next();
        }

        const bodyKeys = Object.keys(req.body);

        const flowInfo = {
            Flow: appFlow.id,
            Steps: [null, {
                StartDate: new Date(),
                Status: '1'
            }, {
                StartDate: new Date(),
                Status: '0'
            }],
            Status: "0",
            CurrentStep: 2,
        };

        const doc = {
            培训: theTraining.名称,
        };

        const fields = [
            '单位',
            '联系人',
            '电话',
            '邮件',
            '描述',
        ];

        for (let i = 0; i < bodyKeys.length; i += 1) {
            const bk = bodyKeys[i];

            if (fields.indexOf(bk) >= 0) {
                doc[bk] = req.body[bk];
            }
        }

        res.locals.body = {
            User: req.user.id,
            ...flowInfo,
            ...doc,
        };
        
        return next();
    },
    router.CreateDocument('trainingapplication'),
);

module.exports = router;
